package com.zzj.until;
 
import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.InputStream;  
import java.net.HttpURLConnection;  
import java.net.URL;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.junit.Test;

/** 
 * @说明 从网络获取图片到本地 
 * @author 郑子建
 * @version 1.0 
 * @since 
 */    
public class HttpTool {  
	 /** 
     * 测试 
     * @param args 
     */
//	 @Test
//    public void main(String[] args) {
//        String url = "http://pic.58pic.com/58pic/17/41/38/88658PICNuP_1024.jpg";
//        downLoadImgFromUrl(url,"d://123//12.jpg");
//    	String a = getHttpContent("http://docs.oracle.com/javase/7/docs/api/java/io/File.html");
//    	System.out.println(a);
//    }
    
    /**
     * 获取网页内容，若没有内容则放回 ""
     * @param url
     * @return
     */
    public static String getHttpContent(String url){
    	String jsonData="";
    	try{
			HttpClient httpClient = new HttpClient(); //构造HttpClient实例
			//创建GET方法的实例
			GetMethod getMethod = new GetMethod(url); //使用系统提供的默认的恢复策略
			getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
			// 执行getMethod
			int statusCode = httpClient.executeMethod(getMethod);
			if(statusCode != HttpStatus.SC_OK){
				System.out.println(""+getMethod.getStatusLine());
			}
			byte[] responseBody = getMethod.getResponseBody(); //读取内容
			jsonData = new String(responseBody,"UTF-8").replaceAll("&quot;", "\""); //获取得到json数据
			} catch (Exception e) {
				e.printStackTrace();
			}
		return jsonData;
    }
    
    /**
     * 从网络上下载图片到本地
     * @param httpurl 网络url "http://pic.58pic.com/58pic/17/41/38/88658PICNuP_1024.jpg"
     * @param localurl 本地url "d://123//12.jpg"
     *  
     * @return
     */
    public static boolean downLoadImgFromUrl(String httpurl,String localurl){
    	boolean flag=true;
    	 byte[] btImg = getImageFromNetByUrl(httpurl);
    	 if(null != btImg && btImg.length > 0){      
              flag = writeImageToDisk(btImg, localurl);
         }else{
        	 flag=false;
             System.out.println("没有从该连接获得图片内容");
         }
		return flag; 
    }
    
////////////////////////////////////////////////////////////////////////////////////////   
    /** 
     * 将图片写入到磁盘 
     * @param img 图片数据流 
     * @param fileName 文件保存时的名称 
     */
    private static boolean writeImageToDisk(byte[] img, String fileName){  
        try {
        	FileTool.makeParaDirectory(fileName);
            File file = new File(fileName);
            FileOutputStream fops = new FileOutputStream(file);  
            fops.write(img);  
            fops.flush();  
            fops.close();    
        } catch (Exception e) {  
            System.out.println(fileName+"将byte转成本地文件时出错！");
        	//e.printStackTrace();
            return false;
        } 
        return true;
    }  
    /** 
     * 根据地址获得数据的字节流 
     * @param strUrl 网络连接地址 
     * @return 
     */  
    private static byte[] getImageFromNetByUrl(String strUrl){  
        try {  
            URL url = new URL(strUrl);  
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
            conn.setRequestMethod("GET");  
            conn.setConnectTimeout(5 * 1000);  
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据  
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据  
            return btImg;  
        } catch (Exception e) {  
            System.out.println(strUrl+"该图片地址为空！");
        	//e.printStackTrace();  
        }  
        return null;  
    }  
    /** 
     * 从输入流中获取数据 
     * @param inStream 输入流 
     * @return 
     * @throws Exception 
     */  
    private static byte[] readInputStream(InputStream inStream) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        while( (len=inStream.read(buffer)) != -1 ){  
            outStream.write(buffer, 0, len);  
        }  
        inStream.close();  
        return outStream.toByteArray();  
    }  
}  
